package com.predic8.membrane.servlet.embedded;

import com.predic8.membrane.core.config.spring.LocationXmlWebApplicationContext;
import com.predic8.membrane.servlet.RouteHelper;
import com.predic8.membrane.core.Router;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.XmlWebApplicationContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * This embeds Membrane as a servlet.
 */
public class MembraneServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Log log = LogFactory.getLog(MembraneServlet.class);

    private XmlWebApplicationContext appCtx;
    private Router router;

    @Override
    public void init(ServletConfig config) throws ServletException {
        try {
            appCtx = new LocationXmlWebApplicationContext();

            log.debug("loading beans configuration from: " + getProxiesXmlLocation(config));
            router = RouteHelper.initializeRoutersFromSpringWebContext(appCtx, config.getServletContext(), getProxiesXmlLocation(config));
            if (router == null) {
                throw new RuntimeException("No <router> with a <servletTransport> was found. To use <router> with <transport>, use MembraneServletContextListener instead of MembraneServlet.");
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    @Override
    public void destroy() {
        appCtx.stop();
    }

    private String getProxiesXmlLocation(ServletConfig config) {
        return config.getInitParameter("proxiesXml");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        try {
            new HttpServletHandler(req, resp, router.getTransport()).run();
        } catch (IOException e) {
            throw new ServletException(e);
        }
    }

}
